<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="状态">
          <el-select v-model="searchModel.status" placeholder="请选择状态">
            <el-option label="全部" :value="null" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联类型">
          <el-select v-model="searchModel.productType" placeholder="请选择状态">
            <el-option label="全部" :value="null" />
            <el-option label="会员开通" :value="1" />
            <el-option label="洗车" :value="2" />
            <el-option label="加油" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="关联ID">
          <el-input
            v-model.trim="searchModel.productId"
            placeholder="请输入关联ID"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="search()"
            >查询</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            type="primary"
            color="#ea5b24"
            @click="showDialog(0, null)"
            v-if="pinia.isShow[98]"
            >添加</el-button
          >
        </el-form-item> -->
      </el-form>
    </div>

    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column
          prop="productType"
          :formatter="judgeProductType"
          label="关联类型"
        />
        <el-table-column prop="productId" label="关联ID" />
        <el-table-column label="场景名称/支付方式">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="showDialog(0, scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot:default="scope"
            >{{
              scope.row.status == null
                ? ""
                : scope.row.status == 0
                ? "禁用"
                : "启用"
            }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="80" label="操作">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="showDialog(1, scope.row)"
              v-if="pinia.isShow[163]"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!--添加/编辑管理员表单 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑关联支付场景"
      center="true"
      modal="true"
      width="450px"
    >
      <el-form :model="configModel" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="关联场景："
          :label-width="editFormLabelWidth"
          prop="scenarioIdArr"
        >
          <el-select
            v-model="configModel.scenarioIdArr"
            multiple
            placeholder="请选择关联场景"
            class="select-roles"
          >
            <el-option
              v-for="item in scenario.data"
              :value="item['value']"
              :label="item['label']"
              :key="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="状态："
          :label-width="editFormLabelWidth"
          prop="status"
        >
          <el-radio-group v-model="configModel.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="formSubmit(ruleFormRef)"
            color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 查看登陆地dialog -->
    <el-dialog
      v-model="payMethodDialogVisible"
      draggable
      center="true"
      modal="true"
      width="800px"
    >
      <el-table
        :data="payMethodData.data"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column prop="title" width="140" label="场景名称" />
        <el-table-column prop="bizPlatform" width="140" label="终端产品">
          <template v-slot:default="scope"
            >{{ judgePlatform(scope.row.bizPlatform) }}
          </template>
        </el-table-column>
        <el-table-column prop="appPlatform" width="140" label="终端平台">
          <template v-slot:default="scope"
            >{{ judgePlatform(scope.row.appPlatform) }}
          </template>
        </el-table-column>
        <el-table-column prop="payMethodNames" label="支付方式" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  findAssnPaySceneListApi,
  editAssnPaySceneApi,
  findPaySceneListApi,
  findPayMethodByIdApi,
} from "../../../api/index";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

const editFormLabelWidth = "100px";

// 控制编辑dialog
const dialogVisible = ref(false);
// 控制弹出支付方式dialog
const payMethodDialogVisible = ref(false);
// 登陆地列表数据
let payMethodData: any = reactive([]);

// 搜索模型
const searchModel: any = reactive({
  productId: null,
  productType: null,
  status: null,
  pageNum: page,
  pageSize: size,
});
// 添加/编辑模型
const configModel = reactive({
  id: null,
  scenarioIdArr: null,
  scenarioIds: null,
  status: null,
});

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  scenarioIdArr: [
    { required: true, message: "请选择关联场景", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

// 过滤状态显示
function judgeProductType(item) {
  switch (item.productType) {
    case 1:
      return "会员开通";
    case 2:
      return "洗车";
    case 3:
      return "加油";
    default:
      return "";
  }
}

// 过滤终端显示
function judgePlatform(item) {
  switch (item) {
    case "wnsj":
      return "华行通";
    case "kyx":
      return "阔悦行";
    case "cxw":
      return "车讯网";
    case "ybt":
      return "壹佰通";
    case "wx":
      return "微信小程序";
    case "alipay":
      return "支付宝小程序";
    case "android":
      return "android客户端";
    case "ios":
      return "IOS客户端";
    default:
      return "";
  }
}

// 翻页
let flipData = reactive({
  pageNum: page,
  pageSize: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.pageNum = page.value;
  searchConfig(flipData);
};

// 搜索支付场景
const search = () => {
  page.value = 1;
  searchParmSearch();
  searchConfig(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

//条件查询支付场景列表
const searchConfig = (searchModel) => {
  findAssnPaySceneListApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.items;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 控制添加/编辑dialog显示
const showDialog = (type: number, row) => {
  if (type === 0) {
    findPayMethodById(row.id);
    payMethodDialogVisible.value = true;
  } else {
    ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
    configModel.id = row.id;
    configModel.status = row.status;
    findAllScenario({
      pageNum: 1,
      pageSize: 5000,
    });
    configModel.scenarioIdArr = [];
    if (row.scenarioIds) {
      row.scenarioIds.split(",").forEach((val) => {
        configModel.scenarioIdArr.push(parseInt(val));
      });
    }
    dialogVisible.value = true;
  }
};

/**
 * 编辑
 */
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      configModel.scenarioIds = configModel.scenarioIdArr.join(",");
      editAssnPaySceneApi(configModel).then((res) => {
        if (res.data.code === 2000) {
          ElMessage({
            message: "编辑成功.",
            type: "success",
          });
          searchConfig(searchModel);
        } else {
          switch (res.data.code) {
            default:
              ElMessage.error("编辑失败.");
              break;
          }
        }
      });

      Object.keys(configModel).forEach((key) => (configModel[key] = ""));
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 查询指定场景的场景名称和支付方式
const findPayMethodById = (id) => {
  findPayMethodByIdApi(id).then((res) => {
    if (res.data.code === 2000) {
      payMethodData.data = res.data.data;
      console.log(payMethodData.data);
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 查询所有的关联场景
let scenario: any = reactive([]);
const findAllScenario = (param) => {
  findPaySceneListApi(param).then((res) => {
    if (res.data.code === 2000) {
      let dataList = res.data.data.items;
      scenario.data = Array.from(dataList).map((item, idx) => ({
        value: item["id"],
        label: item["title"],
      }));
    } else {
      ElMessage.error("查询关联场景失败");
    }
  });
};

onMounted(() => {
  searchConfig(searchModel);
});
</script>

<style>
.select-roles {
  width: 100%;
}
</style>
